package derson.com.multipletheme.colorUi.util;

import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.SparseIntArray;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * Created by xuxingcan on 17-5-10.
 */

public class ThemeModeUiBase {
    private SparseIntArray sparseIntArray;
    private View view;


    public ThemeModeUiBase(View view, AttributeSet attr) {
        this.view = view;
        sparseIntArray = new SparseIntArray();
        if (attr != null) {
            int count = attr.getAttributeCount();
            for (int i = 0; i < count; i++) {
                String str = attr.getAttributeValue(i);
                if (null != str && str.startsWith("?")) {
                    int resId = attr.getAttributeNameResource(i);
                    if (resId != 0) {
                        sparseIntArray.put(resId, Integer.valueOf(str.substring(1, str.length())));
                    }
                }
            }
        }
    }

    public void setTheme(Resources.Theme theme) {
        if (sparseIntArray == null || sparseIntArray.size() == 0 || view == null) {
            return;
        }
        int count = sparseIntArray.size();
        int[] params = new int[count];
        for (int i = 0; i < count; i++) {
            params[i] = sparseIntArray.valueAt(i);
        }
        TypedArray ta = theme.obtainStyledAttributes(params);
        Drawable drawable;
        for (int i = 0; i < count; i++) {
            int resName = sparseIntArray.keyAt(i);
            switch (resName) {
                case android.R.attr.background:
                    drawable = ta.getDrawable(i);
                    view.setBackground(drawable);
                    break;
                case android.R.attr.src:
                    if (view instanceof ImageView) {
                        drawable = ta.getDrawable(i);
                        ((ImageView) view).setImageDrawable(drawable);
                    }
                    break;
                case android.R.attr.textColor:
                    if (view instanceof TextView) {
                        int resourceId = ta.getColor(i, 0);
                        ((TextView) view).setTextColor(resourceId);
                    }
                    break;
            }
        }
        ta.recycle();
    }
}
